package com.wiscamp.ninechapters.problems.infrastructure.mappers.tasks;

import com.wiscamp.ninechapters.problems.infrastructure.po.tasks.TaskView;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.Collection;

/**
 * 习题集分发任务仓储对象
 *
 * @author yifeng
 */
@Repository
public interface TaskViewMapper extends JpaRepository<TaskView, Long>, JpaSpecificationExecutor<TaskView> {
    /**
     * 分页查询
     *
     * @param spec
     * @param pageable
     * @return
     */
    Page<TaskView> findAll(Specification<TaskView> spec, Pageable pageable);

    /**
     * @param assignmentId
     * @param detailId
     * @param setId
     * @param userId
     * @return
     */
    @Query(value = "select e from TaskView e where e.assignmentId = :assignmentId and e.detailId = :detailId and e.setId = :setId and e.userId = :userId")
    TaskView findByAssignmentAndDetail(long assignmentId, long detailId, long setId, long userId);

    TaskView findFirstBySetIdAndUserIdAndTaskStatusId(long setId, long userId, int taskStatusId);

    @Query(value = "select e from TaskView e where e.assignmentId = :assignmentId and e.setId = :setId order by e.taskId desc")
    Collection<TaskView> findListByAssignmentAndSet(long assignmentId, long setId);

    @Query(value = "select e from TaskView e where e.userId = :userId and e.taskStatusId = :statusId order by e.taskId desc")
    Page<TaskView> findPagedTasksByUserAndStatus(long userId, int statusId, Pageable pageable);

    @Query(value = "select e from TaskView e where e.userId = :userId and e.taskStatusId = :statusId order by e.taskId desc")
    Collection<TaskView> findListByUserAndStatus(long userId, int statusId);

    @Query(value = "select count(e.taskId) from TaskView e where e.userId = :userId")
    int findTaskQuantityByUser(long userId);

    @Query(value = "select count(e.taskId) from TaskView e where e.userId = :userId and e.taskStatusId = :statusId order by e.taskId desc")
    int findTaskQuantityByUserAndStatus(long userId, int statusId);

    @Query(value = "select count(e.taskId) from TaskView e, AssignmentPO a where e.assignmentId = a.assignmentId and a.assignmentTime between :startDate and :endDate")
    int findTaskQuantityByDate(LocalDate startDate, LocalDate endDate);


}